<template>
  <el-dialog v-model="dialogVisible" :close-on-click-modal="false" custom-class="mydialog" title="变更终端直销匹配信息"
             width="50%"
             @close="close">

    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="终端名称">
            {{ datas.terminalName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>

        <el-col :span="12">
          <el-form-item label="所在地区" prop="region">
            {{ datas.provinceName }}/{{ datas.cityName }}/{{ datas.areaName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终端类型" prop="terminalType">
            {{ getLabel('app_mode', datas.terminalType) }}
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="产品信息">
            {{ getProductName(datas) }}
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="当前终端价" prop="productPopularName">
            {{ datas.terminalPrice }}元
            <span v-if="datas.sellUnit">/{{ getLabel("sell_unit", datas.sellUnit) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="当前交易价" prop="packSpecs">
            {{ datas.tradePrice }}元
            <span v-if="datas.sellUnit">/{{ getLabel("sell_unit", datas.sellUnit) }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="新终端价" prop="newTerminalPrice">
            <div style="display: flex; justify-content: space-between">
              <div style="width: 80%">
                <app-price-popover ref="pricePop" :disabled='disabled' :props-product="propsProduct"
                                   @confirm="priceConfirm">
                  <el-select v-model="openForm.newTerminalPrice" :disabled="booleDis"
                             placeholder="请选择终端价" style="width: 100%" @focus="priceFocus">
                    <template #empty/>
                  </el-select>
                </app-price-popover>
              </div>
              <div style=" text-align: center">
                元
                <span v-if="datas.sellUnit">
                  /{{ getLabel("sell_unit", datas.sellUnit) }}</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="big">
          <el-form-item label="新交易价" prop="newTradePrice">
            <el-input v-model="openForm.newTradePrice" clearable placeholder="请输入交易价" @change="handlPrice">
              <template #append>
                <span>元/盒</span>
              </template>
            </el-input>
          </el-form-item>
          <div v-if="boolePrice" class="box">
            输入的交易价低于该地区产品底价
          </div>
        </el-col>

        <el-col :span="12">
          <el-form-item label="负责营销职员" prop="headId">
            <el-select v-model="openForm.headId" placeholder="请选择营销职员" style="width: 100%" @change="handlChangeHead">
              <el-option v-for="item in headList" :key="item.id" :label="item.realName" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: center; align-items: center">
        <el-button class="border-btn" size="small" style="margin-right: 20px" @click="close">取消
        </el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";
import {validateVENum, validateVENumber} from "@/utils/validate";
import {crmStore} from "@CRM/store";

export default {
  name: "changeDialog",
  emits: ['success'],
  setup(props, context) {
    const validateNum = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback(new Error("请选择终端价"));
      } else {
        if (validateVENumber(value)) {
          callback(new Error("格式不正确(最多保留两位小数)"));
        } else {
          callback();
        }
      }
    };
    const validateNum1 = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback(new Error("请输入交易价"));
      } else {
        if (validateVENumber(value)) {
          callback(new Error("格式不正确(最多保留两位小数)"));
        } else {
          if (value > data.openForm.terminalPrice) {
            callback(new Error("交易价不能大于终端价"));
          } else {
            callback();
          }
        }
      }
    };
    const validateVal = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback();
      } else {
        if (validateVENum(value)) {
          callback(new Error("格式不正确(正整数)"));
        } else {
          callback();
        }
      }
    };
    const validateVal1 = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback(new Error("请输入开发保证金"));
      } else {
        if (validateVENum(value)) {
          callback(new Error("格式不正确(正整数)"));
        } else {
          callback();
        }
      }
    };

    const api = inject("api");
    const currentInstance = getCurrentInstance();
    var data = reactive({
      datas: {},
      openForm: {
        newTerminalPrice: "",
        productPriceId: "",
        newTradePrice: "",
        headId: "",
        headName: "",
      },
      rules: {
        terminalName: [
          {required: true, message: "请选择终端", trigger: "change"},
        ],
        productName: [
          {required: true, message: "请选择产品名称", trigger: "blur"},
        ],
        agentName: [{required: true, message: "请选择名称", trigger: "blur"}],
        sellEarnestMoney: [{validator: validateVal, trigger: "blur"}],
        devEarnestMoney: [
          {required: true, validator: validateVal1, trigger: "blur"},
        ],
        newTerminalPrice: [
          {required: true, validator: validateNum, trigger: "blur"},
        ],
        newTradePrice: [
          {required: true, validator: validateNum1, trigger: "blur"},
        ],
        expireTime: [
          {required: true, message: "请选择日期", trigger: "blur"},
        ],
        headId: [
          {required: true, message: "请选择负责营销职员", trigger: "change"},
        ],
      },
      openRef: null,
      nuitData: crmStore.getters["dictionary/getDictionary"]["sell_num_unit"],
      salesModel: crmStore.getters["dictionary/getDictionary"]["agentType"],
      accessMode: crmStore.getters["dictionary/getDictionary"]["access_mode"],
      terminalData: crmStore.getters["dictionary/getDictionary"]["app_mode"],
      id: "",
      headList: crmStore.getters["company/getHeadOptions"],
      pricePop: null,
      propsProduct: {
        terminalType: "",
        productId: 0,
        region: [],
        terminalId: 0,
      },
      booleDis: false,
      dialogVisible: false,
      disabled: false,
      boolePrice: false,
    });


    // 终端价
    const priceConfirm = (val) => {
      data.openForm.productPriceId = val?.id;
      data.openForm.newTerminalPrice = Number(val.terminalPrice);
      data.openForm.newTradePrice = Number(val.terminalPrice);
      data.openForm.guidingPrice = Number(val.guidingPrice);
      data.openForm.accessMode = val.accessMode;
    };

    //交易价
    const handlPrice = (val) => {
      data.openForm.newTradePrice = Number(val);
      if (data.openForm.newTradePrice < data.openForm.guidingPrice) {
        data.boolePrice = true;
      } else {
        data.boolePrice = false;
      }
    };

    // 打开终端价弹框
    const priceFocus = (val) => {
      if (val) {
        data.pricePop.openPopover();
      }
    };

    // 取消终端价弹框
    const priceClear = () => {
      data.openForm.terminalPrice = "";
    };

    // 负责人事件
    const handlChangeHead = (val) => {
      const index = data.headList.findIndex((a) => a.id === val);
      if (index !== -1) {
        data.openForm.headName = data.headList[index].realName;
      }
    };

    // 关闭弹框
    const close = () => {
      data.dialogVisible = false;
      remove();
    };

    // 清除弹框
    const remove = () => {
      data.disabled = true;
      data.openRef.clearValidate();
      data.openRef.resetFields();
      data.openForm.sellUnit = "";
      data.booleDis = false;
      data.dialogVisible = false;
    };

    const handlClear = () => {
      data.openForm = {
        newTerminalPrice: "",
        productPriceId: "",
        newTradePrice: "",
        headId: "",
        headName: "",
      };
      data.boolePrice = false;
    };

    // 打开弹框
    const open = (val) => {
      handlClear();
      data.datas = {...val}
      data.propsProduct = {
        terminalType: val.terminalType,
        productId: val.productId,
        region: val.region,
        terminalId: val.terminalId,
      }
      data.openForm.newTerminalPrice = val.terminalPrice
      data.openForm.productPriceId = val.productPriceId
      data.openForm.newTradePrice = val.tradePrice
      data.openForm.headId = val.headId
      data.openForm.headName = val.headName

      data.disabled = false;
      data.dialogVisible = true;
    };

    // 提交表单
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          if (data.openForm.headId == data.datas.headId && data.openForm.productPriceId == data.datas.productPriceId && data.openForm.newTradePrice == data.datas.tradePrice) {
            currentInstance.proxy.customMessage({type: 'error', message: '请先修改信息'})
            return;
          }

          let formList = {
            id: Number(data.datas.id),
            headId: Number(data.openForm.headId),
            headName: data.openForm.headName,
            newTradePrice: Number(data.openForm.newTradePrice),
            newTerminalPrice: Number(data.openForm.newTerminalPrice),
            productPriceId: Number(data.openForm.productPriceId),
          };

          handlsubForm(formList);
        }
      });
    };

    const handlsubForm = (data) => {
      api.terminal.REGISTERED_TERMINAL_DIRECT_CHANGE(data).then((res) => {
        if (res.code === 0) {
          currentInstance.proxy.customMessage({
            type: "success",
            message: "提交成功",
          });
          context.emit("success");
          close();
        } else {
          currentInstance.proxy.customMessage({
            type: "error",
            message: res.msg,
          });
        }
      });
    };

    onMounted((_) => {

    });

    return {
      ...toRefs(data),

      handlChangeHead,
      close,
      open,
      handlSubmit,
      priceConfirm,
      priceFocus,
      priceClear,
      handlPrice,
    };
  },
};
</script>

<style lang="scss" scoped>
/* @import url(); 引入css类 */
.col_title {
  height: 36px;
  width: 100%;
  line-height: 36px;
  background: rgb(248, 248, 248);
  padding-left: 10px;
  box-sizing: border-box;
}

:deep(.el-input__inner) {
  background-color: #fff;
}

.big {
  position: relative;

  .box {
    position: absolute;
    font-size: 12px;
    line-height: 14px;
    color: red;
    top: 34px;
    left: 132px;
  }
}
</style>
